<template>
  <el-form label-width="100px">
    <el-form-item label="SPU 名称"> SPU名称 </el-form-item>
    <el-form-item label="SKU 名称">
      <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input type="number" v-model="skuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)">
      <el-input type="number" v-model="skuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input
        type="textarea"
        placeholder="规格描述"
        rows="4"
        v-model="skuInfo.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item
          v-for="attr in attrList"
          :key="attr.id"
          :label="attr.attrName"
        >
          <el-select placeholder="请选择" v-model="attr.attrIdValueId">
            <el-option
              v-for="item in attr.attrValueList"
              :key="item.id"
              :value="`${item.attrId}:${item.id}`"
              :label="item.valueName"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form label-width="100px" :inline="true">
        <el-form-item
          v-for="attr in saleAttrList"
          :label="attr.saleAttrName"
          :key="(attr.id as number) "
        >
          <el-select placeholder="请选择" v-model="attr.attrIdAttrValueId">
            <el-option
              v-for="item in attr.spuSaleAttrValueList"
              :value="`${item.baseSaleAttrId}:${item.id}`"
              :label="item.saleAttrValueName"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>

    <el-form-item label="图片列表">
      <!-- handleSelectionChange -->
      <el-table
        border
        stripe
        :data="spuImgList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img :src="row.imgUrl" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-tag
              v-if="row.isDefault === '1'"
              type="success"
              size="small"
              effect="plain"
              closable
              @close=""
              >默认图片</el-tag
            >

            <el-button v-else type="primary" @click="changeIsDefault(row)"
              >设为默认</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="default" @click="emit('setState', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SkuForm",
});
</script>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { requestSaveSkuInfo } from "@/api/sku";
import { ElMessage } from "element-plus";
import type {
  SkuAttrValueListType,
  SkuImageItemType,
  SkuImageListType,
  SkuInfoItemType,
  SkuSaleAttrValueListType,
} from "@/api/sku";
import { requestAttrList, type attrListType } from "@/api/attr";
import {
  requestSpuImgList,
  requestSpuSaleAttrList,
  type SpuImageListType,
  type SpuInfoType,
  type SpuSaleAttrListType,
} from "@/api/spu";
import { storeToRefs } from "pinia";
import useAttrStore from "@/stores/attr";
//1.接受props传值
const props = defineProps<{
  spuInfo: SpuInfoType;
}>();
const spuInfo = props.spuInfo;

//2.接收自定义事件函数用来切换组件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void;
}>();
//3.拿到pinia中的三级分类数据
const attrStore = useAttrStore();
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore);

//初始化收集数据
const skuInfo = ref<SkuInfoItemType>({
  //需要我们直接进行双向绑定收集的
  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",

  //需要从props中的spu中直接拿
  spuId: 0,
  tmId: 0,
  category3Id: 0,

  //需要收集的默认图片
  skuDefaultImg: "",

  //需要计算收集的
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
});
//4.初始化一些值 保存初始化请求的数据
const attrList = ref<attrListType>([]); //平台属性属性列表
const saleAttrList = ref<SpuSaleAttrListType>([]); //销售属性列表
const spuImgList = ref<SpuImageListType>([]); //图片列表
const getInitData = async () => {
  const promise1 = requestAttrList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const promise2 = requestSpuSaleAttrList(spuInfo.id as number);
  const promise3 = requestSpuImgList(spuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);
  attrList.value = result[0];
  saleAttrList.value = result[1];
  spuImgList.value = result[2];
};
//初始化操作
onMounted(() => {
  getInitData();
});

//设置图片默认事件函数
const changeIsDefault = (row: SkuImageItemType) => {
  //修改图片列表中所有的default为false
  spuImgList.value.forEach((item) => {
    item.isDefault = "0";
  });
  //当前的图片为默认选择
  row.isDefault = "1";
};

interface ImgListType {
  id: number;
  imgName: string;
  imgUrl: string;
  spuId: number;
}
// //定义一个数据,收集选中的图片组成的数据(千万不要修改原来的数组)
const skuImgList = ref<SpuImageListType>([]);
const handleSelectionChange = (val: ImgListType[]) => {
  skuImgList.value = val;
};

//点击保存事件函数
const save = async () => {
  skuInfo.value.spuId = props.spuInfo.id;
  skuInfo.value.tmId = props.spuInfo.tmId as number;
  skuInfo.value.category3Id = props.spuInfo.category3Id;
  // //收集平台属性
  attrList.value.forEach((item) => {
    //判断用户是否选择了平台属性
    if (item.attrIdValueId) {
      //解构下拉框的值
      const [attrId, valueId] = item.attrIdValueId.split(":");
      //保存在对象中
      const newAttr = {
        attrId: +attrId,
        valueId: +valueId,
      };
      //插入到平台属性列表中
      (skuInfo.value.skuAttrValueList as SkuAttrValueListType).push(newAttr);
    }
  });
  //收集销售属性
  saleAttrList.value.forEach((item) => {
    //判断用户是否选择了销售属性
    if (item.attrIdAttrValueId) {
      //解构下拉框的值
      const [saleAttrId, saleAttrValueId] = item.attrIdAttrValueId.split(":");
      const newSaleAttr = {
        saleAttrId: +saleAttrId,
        saleAttrValueId: +saleAttrValueId,
      };
      //插入到销售属性列表中
      (skuInfo.value.skuSaleAttrValueList as SkuSaleAttrValueListType).push(
        newSaleAttr
      );
    }
  });

  // //处理图片数据
  spuImgList.value.forEach((item) => {
    const newImg = {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      isDefault: item.isDefault,
      spuId: item.spuId,
    };
    //判断是否有默认图片
    if (item.isDefault === "1") {
      skuInfo.value.skuDefaultImg = item.imgUrl;
    }
    //插入到图片列表中
    (skuInfo.value.skuImageList as SkuImageListType).push(newImg);
  });

  try {
    //发送请求
    await requestSaveSkuInfo(skuInfo.value);
    ElMessage.success("保存成功");
  } catch (e) {
    ElMessage.error("保存失败");
  }
  //回到spulist页面
  emit("setState", 0);
};
</script>
